package LeetCode._01算法入门.day14位运算;

import org.junit.Test;

/**
 * @author 挚爱之夕
 * @date 2022-03-05 - 03 - 05 - 8:57
 * @Description 颠倒给定的 32 位无符号整数的二进制位。
 * @Version 简单
 */
public class _190颠倒二进制位 {
    @Test
    public void solve(){
        int i = 0b00000010100101000001111010011100;
        System.out.println(reverseBits1(i));
    }
    /*官方思路*/

    //1.逐位颠倒

    // you need treat n as an unsigned value
    public int reverseBits1(int n) {
        int rev = 0;
        for (int i = 0; i < 32 && n != 0; ++i) {
            //取得n最低位,依次放在rev从左到右的高位，因为rev该位为0 按位或(|) 按位异或(^)都行
            rev |= (n & 1) << (31 - i);
            //Java中没有无符号整数类型，因此对n的右移操作应使用逻辑右移
            n >>>= 1;
        }
        return rev;
    }

    //2.分治法
    private static final int M1 = 0x55555555; // 01010101010101010101010101010101
    private static final int M2 = 0x33333333; // 00110011001100110011001100110011
    private static final int M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
    private static final int M8 = 0x00ff00ff; // 00000000111111110000000011111111

    public int reverseBits2(int n) {
        n = n >>> 1 & M1 | (n & M1) << 1;
        n = n >>> 2 & M2 | (n & M2) << 2;
        n = n >>> 4 & M4 | (n & M4) << 4;
        n = n >>> 8 & M8 | (n & M8) << 8;
        return n >>> 16 | n << 16;
    }
}
